﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhoneBilling.Models;
using PhoneBilling.Report;
using System.IO;
using System.Text;
using System.Web.Routing;
using System.Drawing;

namespace PhoneBilling.Controllers
{
    public class ManageController : Controller
    {
        //
        // GET: /Manage/


        public ActionResult Index()
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage");

            return View();
        }

        public ActionResult Traiff(string id, string area, string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "费率管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/Traiff");



            TraiffModel traiffModel = new TraiffModel();
            traiffModel.CurrentTraiff = id;
            traiffModel.Message = message;
            traiffModel.TraiffList = loadTraiff();
            if (id == null)
            {
                if (traiffModel.TraiffList.Count > 0)
                    traiffModel.CurrentTraiff = traiffModel.TraiffList[0].ID;

            }

            if (area != null)
            {

                var list = from tariff in entities.Tariff
                           where tariff.TariffID.Trim() == id &&
                                 tariff.AreaCode.Trim().StartsWith(area)
                           orderby tariff.AreaCode
                           select tariff;
                traiffModel.TraiffDetailList = new List<UITraiffDetail>();
                traiffModel.区号 = area;
                foreach (var item in list)
                {
                    UITraiffDetail detail = new UITraiffDetail();
                    detail.区号 = item.AreaCode.Trim();
                    detail.地名 = (item.ChnAddress == null) ? null : item.ChnAddress.Trim();
                    detail.话类 = (item.AreaType == null) ? null : item.AreaType.Trim();
                    detail.基本费 = (item.BaseFee == null) ? 0 : item.BaseFee.Value;
                    detail.服务费 = (item.ServiceFee == null) ? 0 : item.ServiceFee.Value;
                    detail.附加费 = (item.ExtraFee == null) ? 0 : item.ExtraFee.Value;
                    detail.基本费计次秒 = (item.BaseUnitSecond == null) ? 0 : item.BaseUnitSecond.Value;
                    detail.服务费计次秒 = (item.ServeUnitSecond == null) ? 0 : item.ServeUnitSecond.Value;
                    detail.分段计费方法 = (item.SliceID == null) ? null : item.SliceID.Trim();
                    



                    traiffModel.TraiffDetailList.Add(detail);
                }
            }
            else
                traiffModel.TraiffDetailList = loadTraffDetail(traiffModel.CurrentTraiff);

            foreach (var detail in traiffModel.TraiffDetailList)
            {
                if (detail.话类.Length > 0)
                {
                    string str = "";
                    foreach (char c in detail.话类)
                    {
                        if (Char.IsLetter(c))
                        {
                            str += (from a in StaticData.AreaTypeList
                                    where a.Name == c.ToString()
                                    select a.FullName).SingleOrDefault() + " ";
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (str != "")
                        detail.话类 = str;
                }

                if (detail.分段计费方法 != null)
                {

                    detail.分段计费方法 = (from a in StaticData.AreaTypeList
                                     where a.Name == detail.分段计费方法
                                     select a.FullName).SingleOrDefault();
                }
            }

            return View(traiffModel);
        }

        private List<UITraiff> loadTraiff()
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from obj in entities.OBJDefine
                       where obj.ObjectID.Trim() == "TARIFFID"
                       orderby obj.ItemID
                       select obj;
            var traiffList = new List<UITraiff>();
            foreach (var item in list)
            {
                UITraiff traiff = new UITraiff();
                traiff.ID = item.ItemID.Trim();
                traiff.Name = string.Format("{0}.{1}", item.ItemID.Trim(), item.ItemName.Trim());
                traiff.Remark = item.Comment == null ? null : item.Comment.Trim();
                traiffList.Add(traiff);
            }

            return traiffList;
        }

        private List<UITraiffDetail> loadTraffDetail(string id)
        {
            if (id == null)
                return null;

            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from tariff in entities.Tariff
                       where tariff.TariffID.Trim() == id
                       orderby tariff.AreaCode
                       select tariff;
            var traiffDetailList = new List<UITraiffDetail>();
            foreach (var item in list)
            {
                UITraiffDetail detail = new UITraiffDetail();
                detail.区号 = item.AreaCode.Trim();
                detail.地名 = (item.ChnAddress == null) ? null : item.ChnAddress.Trim();
                detail.话类 = (item.AreaType == null) ? null : item.AreaType.Trim();
                detail.基本费 = (item.BaseFee == null) ? 0 : item.BaseFee.Value;
                detail.服务费 = (item.ServiceFee == null) ? 0 : item.ServiceFee.Value;
                detail.附加费 = (item.ExtraFee == null) ? 0 : item.ExtraFee.Value;
                detail.基本费计次秒 = (item.BaseUnitSecond == null) ? 0 : item.BaseUnitSecond.Value;
                detail.服务费计次秒 = (item.ServeUnitSecond == null) ? 0 : item.ServeUnitSecond.Value;
                detail.分段计费方法 = (item.SliceID == null) ? null : item.SliceID.Trim();

                traiffDetailList.Add(detail);
            }

            return traiffDetailList;
        }

        public ActionResult TraiffDetail(string tariffID, string areaCode)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            TraiffDetailModel model = new TraiffDetailModel();
            if (areaCode == null)
                model.IsNew = true;
            else
            {
                var item = (from t in entities.Tariff
                            where t.AreaCode.Trim() == areaCode &&
                                  t.TariffID.Trim() == tariffID
                            select t).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                model.区号 = item.AreaCode.Trim();
                model.地名 = (item.ChnAddress == null) ? null : item.ChnAddress.Trim();
                model.话类 = (item.AreaType == null) ? null : item.AreaType.Trim();
                model.基本费 = (item.BaseFee == null) ? 0 : item.BaseFee.Value;
                model.服务费 = (item.ServiceFee == null) ? 0 : item.ServiceFee.Value;
                model.附加费 = (item.ExtraFee == null) ? 0 : item.ExtraFee.Value;
                model.基本费计次秒 = (item.BaseUnitSecond == null) ? 0 : item.BaseUnitSecond.Value;
                model.服务费计次秒 = (item.ServeUnitSecond == null) ? 0 : item.ServeUnitSecond.Value;
                model.分段计费方法 = (item.SliceID == null) ? null : item.SliceID.Trim();
            }

            model.TraiffID = tariffID;
            model.SliceList = loadSliceList(true);
            model.AreaTypeList = loadAreaTypeList();
            return View(model);
        }

        private List<UIAreaType> loadAreaTypeList()
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from obj in entities.OBJDefine
                       where obj.ObjectID.Trim() == "AREATYPE"
                       orderby obj.ItemID
                       select obj;
            var areaTypeList = new List<UIAreaType>();
            foreach (var item in list)
            {
                UIAreaType areaType = new UIAreaType();
                areaType.ID = item.ItemID.Trim();
                areaType.Name = string.Format("{0}.{1}", item.ItemID.Trim(), item.ItemName.Trim());
                areaTypeList.Add(areaType);
            }

            return areaTypeList;
        }

        public List<UISlice> loadSliceList(bool hasEmpty)
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from obj in entities.OBJDefine
                       where obj.ObjectID.Trim() == "SLICE"
                       orderby obj.ItemID
                       select obj;
            List<UISlice> sliceList = new List<UISlice>();
            if (hasEmpty)
                sliceList.Add(new UISlice() { ID = string.Empty, Name = string.Empty });
            foreach (var item in list)
            {
                UISlice slice = new UISlice();
                slice.ID = item.ItemID.Trim();
                slice.Name = string.Format("{0}.{1}", item.ItemID.Trim(), item.ItemName.Trim());
                slice.Remark = item.Comment == null ? null : item.Comment.Trim();
                sliceList.Add(slice);
            }

            return sliceList;
        }

        [HttpPost]
        public ActionResult TraiffDetail(TraiffDetailModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    var item = (from t in entities.Tariff
                                where t.AreaCode.Trim() == model.区号 &&
                                      t.TariffID.Trim() == model.TraiffID
                                select t).SingleOrDefault();
                    if (item == null)
                    {
                        item = new Tariff();
                        item.TariffID = model.TraiffID;
                        item.AreaCode = model.区号;
                        item.AreaType = model.话类;
                        entities.AddToTariff(item);
                    }
                    item.ChnAddress = model.地名;
                    item.BaseFee = model.基本费;
                    item.ExtraFee = model.附加费;
                    item.ServiceFee = model.服务费;
                    item.BaseUnitSecond = model.基本费计次秒;
                    item.ServeUnitSecond = model.服务费计次秒;
                    if (model.分段计费方法 == null || model.分段计费方法 == string.Empty)
                        item.SliceID = null;
                    else
                        item.SliceID = model.分段计费方法;

                    entities.SaveChanges();

                    return RedirectToAction("Traiff", "Manage", new { id = item.TariffID, message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            model.SliceList = loadSliceList(true);
            model.AreaTypeList = loadAreaTypeList();
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult DeleteTraiffDetail(string tariffID, string areaCode)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from t in entities.Tariff
                            where t.AreaCode.Trim() == areaCode &&
                                  t.TariffID.Trim() == tariffID
                            select t).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);
                entities.SaveChanges();

                return RedirectToAction("Traiff", "Manage", new { id = item.TariffID, message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult TraiffMgt(string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "费率管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/TraiffMgt");

            TraiffMgtModel traiffMgtModel = new TraiffMgtModel();
            traiffMgtModel.TraiffList = loadTraiff();
            traiffMgtModel.Message = message;

            return View(traiffMgtModel);
        }

        public ActionResult TraiffEdit(string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            TraiffEditModel model = new TraiffEditModel();
            if (id != null)
            {
                var item = (from obj in entities.OBJDefine
                            where obj.ObjectID.Trim() == "TARIFFID" &&
                                  obj.ItemID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }


                model.ID = item.ItemID.Trim();
                model.Name = item.ItemName.Trim();
                model.Remark = item.Comment == null ? null : item.Comment.Trim();
            }
            else
                model.IsNew = true;
            return View(model);
        }

        [HttpPost]
        public ActionResult TraiffEdit(TraiffEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    var item = (from obj in entities.OBJDefine
                                where obj.ObjectID.Trim() == "TARIFFID" &&
                                      obj.ItemID.Trim() == model.ID
                                select obj).SingleOrDefault();
                    if (item == null)
                    {
                        item = new OBJDefine();
                        item.ItemID = model.ID;
                        item.ObjectID = "TARIFFID";

                        entities.AddToOBJDefine(item);
                    }
                    item.ItemName = model.Name;
                    item.Comment = model.Remark;

                    entities.SaveChanges();

                    StaticData.LoadTariffList();

                    return RedirectToAction("TraiffMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult DeleteTraiff(string id)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.OBJDefine
                            where obj.ObjectID.Trim() == "TARIFFID" &&
                                  obj.ItemID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);
                var list = from obj in entities.Tariff
                           where obj.TariffID.Trim() == id
                           select obj;
                foreach (var item1 in list)
                    entities.DeleteObject(item1);

                entities.SaveChanges();

                return RedirectToAction("TraiffMgt", "Manage", new { message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult DiscountMgt(string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "优惠表管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }


            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/DiscountMgt");

            DiscountMgtModel discountMgtModel = new DiscountMgtModel();
            discountMgtModel.DiscountList = loadDisount();
            discountMgtModel.Message = message;

            return View(discountMgtModel);
        }

        private List<UIDiscount> loadDisount()
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from obj in entities.Discount
                       select obj;
            var discountList = new List<UIDiscount>();
            foreach (var item in list)
            {
                UIDiscount discount = new UIDiscount();
                discount.ItemNo = item.ItemNo;
                discount.优惠名称 = item.Description.Trim();
                discount.起始时间 = item.BeginTime.Value;
                discount.终止时间 = item.EndTime.Value;
                discount.折扣话类 = item.AreaTypes.Trim();
                discount.基本费折扣 = item.BaseFeeAgio.Trim();
                discount.服务费折扣 = item.ServeFeeAgio.Trim();
                discount.附加费折扣 = item.ExtraFeeAgio.Trim();
                discount.生效日期 = item.ValidFrom.Value;
                discount.失效日期 = item.ValidTo.Value;
                discountList.Add(discount);

                if (discount.折扣话类.Length > 0)
                {
                    string str = "";
                    foreach (char c in discount.折扣话类)
                    {
                        if (Char.IsLetter(c))
                        {
                            str += (from a in StaticData.AreaTypeList
                                    where a.Name == c.ToString()
                                    select a.FullName).SingleOrDefault() + " ";
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (str != "")
                        discount.折扣话类 = str;
                }
            }

            return discountList;
        }

        public ActionResult DiscountEdit(string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            //MenuModel model1 = new MenuModel();
            //model1.Load();
            //model1.SetMenu("Manage", "Manage/DiscountMgt");
            //Session["Menu"] = model1;

            SanDiDbsEntities entities = new SanDiDbsEntities();
            DiscountModel model = new DiscountModel();
            if (id != null)
            {
                int i = Convert.ToInt32(id);
                var item = (from obj in entities.Discount
                            where obj.ItemNo == i
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                model.ItemNo = item.ItemNo;
                model.优惠名称 = item.Description.Trim();
                model.起始时间 = item.BeginTime.Value;
                model.终止时间 = item.EndTime.Value;
                model.基本费折扣 = item.BaseFeeAgio.Trim();
                model.服务费折扣 = item.ServeFeeAgio.Trim();
                model.附加费折扣 = item.ExtraFeeAgio.Trim();
                model.生效日期 = item.ValidFrom.Value;
                model.失效日期 = item.ValidTo.Value;

                var 优惠话类 = item.AreaTypes.Trim();
                if (优惠话类.Length > 0)
                {
                    foreach (char c in 优惠话类)
                        if (Char.IsLetter(c))
                        {
                            model.折扣类别 = "话类";
                            model.优惠话类 = 优惠话类;
                            break;
                        }
                }
                if (model.折扣类别 == null || model.折扣类别 == string.Empty)
                {
                    model.折扣类别 = "区号";
                    model.优惠区号 = 优惠话类;
                }
            }
            else
            {
                model.IsNew = true;
                model.折扣类别 = "话类";
                //model.是否按话类 = true;
                //model.是否按区号 = false;
                model.生效日期 = Const.History;
                model.失效日期 = Const.Future;
            }

            model.优惠话类List = loadAreaTypeList();
            if (model.优惠话类 != null)
                foreach (char c in model.优惠话类)
                    foreach (var item in model.优惠话类List)
                    {
                        if (item.ID == c.ToString())
                            item.IsSelected = true;
                    }
            return View(model);
        }

        [HttpPost]
        public ActionResult DiscountEdit(DiscountModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    Discount item = null;
                    if (model.IsNew)
                    {
                        item = new Discount();
                        var lastItem = (from obj in entities.Discount
                                        orderby obj.ItemNo descending
                                        select obj).FirstOrDefault();
                        if (lastItem == null)
                            item.ItemNo = 1;
                        else
                            item.ItemNo = lastItem.ItemNo + 1;

                        entities.AddToDiscount(item);
                    }
                    else
                    {
                        item = (from obj in entities.Discount
                                where obj.ItemNo == model.ItemNo
                                select obj).SingleOrDefault();

                        if (item == null)
                        {
                            TempData["Error"] = "没有找到数据！";
                            return RedirectToAction("Error", "Shared");
                        }
                    }
                    item.Description = model.优惠名称;
                    item.DateType = "D";
                    item.BeginTime = new DateTime(model.起始时间.Year, model.起始时间.Month, model.起始时间.Day, model.起始时间.Hour, model.起始时间.Minute, model.起始时间.Second);
                    item.EndTime = new DateTime(model.终止时间.Year, model.终止时间.Month, model.终止时间.Day, model.终止时间.Hour, model.终止时间.Minute, model.终止时间.Second);
                    item.ValidFrom = new DateTime(model.生效日期.Year, model.生效日期.Month, model.生效日期.Day, model.生效日期.Hour, model.生效日期.Minute, model.生效日期.Second);
                    item.ValidTo = new DateTime(model.失效日期.Year, model.失效日期.Month, model.失效日期.Day, model.失效日期.Hour, model.失效日期.Minute, model.失效日期.Second);
                    if (model.折扣类别 == "区号")
                        item.AreaTypes = model.优惠区号;
                    else
                        item.AreaTypes = model.优惠话类;
                    item.BaseFeeAgio = model.基本费折扣;
                    item.ServeFeeAgio = model.服务费折扣;
                    item.ExtraFeeAgio = model.附加费折扣;
                    item.Y4MMDD = string.Empty;

                    entities.SaveChanges();

                    return RedirectToAction("DiscountMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            model.优惠话类List = loadAreaTypeList();
            if (model.优惠话类 != null)
                foreach (char c in model.优惠话类)
                    foreach (var item in model.优惠话类List)
                    {
                        if (item.ID == c.ToString())
                            item.IsSelected = true;
                    }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult DiscountDelete(string id)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                int i = Convert.ToInt32(id);
                var item = (from obj in entities.Discount
                            where obj.ItemNo == i
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);
                entities.SaveChanges();

                return RedirectToAction("DiscountMgt", "Manage", new { message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        private List<UIGrade> loadGrade()
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from obj in entities.OBJDefine
                       where obj.ObjectID.Trim() == "GRADE"
                       orderby obj.ItemID
                       select obj;
            var traiffList = new List<UIGrade>();
            foreach (var item in list)
            {
                if (item.ItemID.Trim() == "R")
                    continue;

                UIGrade traiff = new UIGrade();
                traiff.ID = item.ItemID.Trim();
                traiff.Name = string.Format("{0}.{1}", item.ItemID.Trim(), item.ItemName.Trim());
                traiff.Remark = item.Comment == null ? null : item.Comment.Trim();
                traiffList.Add(traiff);
            }

            return traiffList;
        }

        public ActionResult GradesMgt(string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "收费等级管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/GradesMgt");

            GradesMgtModel traiffMgtModel = new GradesMgtModel();
            traiffMgtModel.GradeList = loadGrade();
            traiffMgtModel.Message = message;

            return View(traiffMgtModel);
        }

        public ActionResult GradeEdit(string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            GradeEditModel model = new GradeEditModel();
            if (id != null)
            {
                var item = (from obj in entities.OBJDefine
                            where obj.ObjectID.Trim() == "GRADE" &&
                                  obj.ItemID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }


                model.ID = item.ItemID.Trim();
                model.Name = item.ItemName.Trim();
                model.Remark = item.Comment == null ? null : item.Comment.Trim();
            }
            else
                model.IsNew = true;
            return View(model);
        }

        [HttpPost]
        public ActionResult GradeEdit(GradeEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    var item = (from obj in entities.OBJDefine
                                where obj.ObjectID.Trim() == "GRADE" &&
                                      obj.ItemID.Trim() == model.ID
                                select obj).SingleOrDefault();
                    if (item == null)
                    {
                        item = new OBJDefine();
                        item.ItemID = model.ID;
                        item.ObjectID = "GRADE";

                        entities.AddToOBJDefine(item);
                    }
                    item.ItemName = model.Name;
                    item.Comment = model.Remark;

                    entities.SaveChanges();

                    StaticData.LoadGradeList();

                    return RedirectToAction("GradesMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult GradeDelete(string id)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.OBJDefine
                            where obj.ObjectID.Trim() == "GRADE" &&
                                  obj.ItemID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);
                var list = from tariff in entities.Grades
                           where tariff.GradeID.Trim() == id
                           orderby tariff.GradeID
                           select tariff;

                foreach (var item1 in list)
                    entities.DeleteObject(item1);
                entities.SaveChanges();

                return RedirectToAction("GradesMgt", "Manage", new { message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult GradeDetailMgt(string id, string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "收费等级管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/GradeDetailMgt");

            GradeDetailMgtModel gradeModel = new GradeDetailMgtModel();
            gradeModel.GradeList = loadGrade();
            gradeModel.CurrentGrade = id;
            gradeModel.Message = message;
            if (id == null)
            {
                if (gradeModel.GradeList.Count > 0)
                    gradeModel.CurrentGrade = gradeModel.GradeList[0].ID;

            }
            gradeModel.GradeDetailList = loadGradeDetail(gradeModel.CurrentGrade);

            var item = (from obj in entities.Grades
                        where obj.GradeID == id &&
                              obj.FeeType.Trim() == "R"
                        select obj).SingleOrDefault();
            if (item != null)
            {
                gradeModel.月租费 = item.ServeRatio;
                gradeModel.功能费 = item.BaseToExtra;
                gradeModel.代维费 = item.BaseToServe;
                gradeModel.免费额 = item.ExtraToServe;
                gradeModel.其他费 = item.FeeMin;
            }

            return View(gradeModel);
        }

        private List<UIGradeDetail> loadGradeDetail(string id)
        {
            if (id == null)
                return null;

            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from tariff in entities.Grades
                       where tariff.GradeID.Trim() == id
                       orderby tariff.GradeID
                       select tariff;
            var gradeDetailList = new List<UIGradeDetail>();
            foreach (var item in list)
            {
                if (item.FeeType.Trim() == "R")
                    continue;

                UIGradeDetail detail = new UIGradeDetail();
                detail.GradeID = item.GradeID.Trim();
                detail.话类 = item.FeeType.Trim();
                detail.最小计费延时 = item.MinDelay;
                detail.时长误差 = item.DurationError;
                detail.最小计次次数 = item.DurationMin;
                detail.服务费缩放系数 = item.ServeRatio;
                detail.附加费按基本费的比例收取时的系数 = item.BaseToExtra;
                detail.服务费按基本费的比例收取时的系数 = item.BaseToServe;
                detail.附加费按服务器的比例收取时的系数 = item.ExtraToServe;
                detail.单笔花费最小金额 = item.FeeMin;
                detail.单笔花费最大金额 = item.FeeMax;
                detail.包月话类收费起点 = item.MonthMin;
                detail.包月话类封顶限额 = item.MonthMax;
                detail.取整方法 = item.RoundDefine;

                if (detail.话类.Length > 0)
                {
                    string str = "";
                    foreach (char c in detail.话类)
                    {
                        if (Char.IsLetter(c))
                        {
                            str += (from a in StaticData.AreaTypeList
                                    where a.Name == c.ToString()
                                    select a.FullName).SingleOrDefault() + " ";
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (str != "")
                        detail.话类 = str;
                }


                gradeDetailList.Add(detail);
            }

            return gradeDetailList;

        }

        public ActionResult GradeDetailEdit(string gradeID, string areaType)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            GradeDetailEditModel model = new GradeDetailEditModel();
            if (areaType != null)
            {
                var item = (from obj in entities.Grades
                            where obj.GradeID == gradeID &&
                                  obj.FeeType == areaType
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                model.话类 = item.FeeType.Trim();
                model.最小计费延时 = item.MinDelay;
                model.时长误差 = item.DurationError;
                model.最小计次次数 = item.DurationMin;
                model.服务费缩放系数 = item.ServeRatio;
                model.附加费按基本费的比例收取时的系数 = item.BaseToExtra;
                model.服务费按基本费的比例收取时的系数 = item.BaseToServe;
                model.附加费按服务器的比例收取时的系数 = item.ExtraToServe;
                model.单笔花费最小金额 = item.FeeMin;
                model.单笔花费最大金额 = item.FeeMax;
                model.包月话类收费起点 = item.MonthMin;
                model.包月话类封顶限额 = item.MonthMax;
                var 取整方法 = item.RoundDefine;

                load取整方法(取整方法, model);
            }
            else
            {
                model.IsNew = true;
                model.优惠折扣单价取整 = false;
                model.单笔花费总价取整 = false;
            }

            model.GradeID = gradeID;
            model.AreaTypeList = loadAreaTypeList();
            return View(model);
        }

        private void load取整方法(int 取整方法, GradeDetailEditModel model)
        {
            string 取整方法16 = Helper.From10To16(取整方法);
            char high = 取整方法16[1];
            char low = 取整方法16[0];

            switch (low)
            {
                case '0':
                    model.优惠折扣单价取整 = false;
                    model.尾数优惠 = string.Empty;
                    model.取整优惠 = string.Empty;
                    break;
                case '5':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "分";
                    model.取整优惠 = "四舍五入";
                    break;
                case '6':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "分";
                    model.取整优惠 = "逢尾数进位";
                    break;
                case '7':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "分";
                    model.取整优惠 = "逢尾数舍去";
                    break;
                case '9':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "角";
                    model.取整优惠 = "四舍五入";
                    break;
                case 'A':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "角";
                    model.取整优惠 = "逢尾数进位";
                    break;
                case 'B':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "角";
                    model.取整优惠 = "逢尾数舍去";
                    break;
                case 'D':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "元";
                    model.取整优惠 = "四舍五入";
                    break;
                case 'E':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "元";
                    model.取整优惠 = "逢尾数进位";
                    break;
                case 'F':
                    model.优惠折扣单价取整 = true;
                    model.尾数优惠 = "元";
                    model.取整优惠 = "逢尾数舍去";
                    break;
            }

            switch (high)
            {
                case '0':
                    model.单笔花费总价取整 = false;
                    model.尾数单笔 = string.Empty;
                    model.取整单笔 = string.Empty;
                    break;
                case '5':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "分";
                    model.取整单笔 = "四舍五入";
                    break;
                case '6':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "分";
                    model.取整单笔 = "逢尾数进位";
                    break;
                case '7':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "分";
                    model.取整单笔 = "逢尾数舍去";
                    break;
                case '9':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "角";
                    model.取整单笔 = "四舍五入";
                    break;
                case 'A':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "角";
                    model.取整单笔 = "逢尾数进位";
                    break;
                case 'B':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "角";
                    model.取整单笔 = "逢尾数舍去";
                    break;
                case 'D':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "元";
                    model.取整单笔 = "四舍五入";
                    break;
                case 'E':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "元";
                    model.取整单笔 = "逢尾数进位";
                    break;
                case 'F':
                    model.单笔花费总价取整 = true;
                    model.尾数单笔 = "元";
                    model.取整单笔 = "逢尾数舍去";
                    break;
            }
        }

        private int get取整方法(GradeDetailEditModel model)
        {
            int high = 0, low = 0;
            if (model.优惠折扣单价取整 == false)
                low = 0;
            else
            {
                switch (model.尾数优惠)
                {
                    case "元":
                        low = 5;
                        break;
                    case "角":
                        low = 9;
                        break;
                    case "分":
                        low = 13;
                        break;
                }
                switch (model.取整优惠)
                {
                    case "四舍五入":
                        break;
                    case "逢尾数进位":
                        low++;
                        break;
                    case "逢尾数舍去":
                        low += 2;
                        break;
                }
            }

            if (model.单笔花费总价取整 == false)
                high = 0;
            else
            {
                switch (model.尾数单笔)
                {
                    case "元":
                        high = 5;
                        break;
                    case "角":
                        high = 9;
                        break;
                    case "分":
                        high = 13;
                        break;
                }
                switch (model.取整单笔)
                {
                    case "四舍五入":
                        break;
                    case "逢尾数进位":
                        high++;
                        break;
                    case "逢尾数舍去":
                        high += 2;
                        break;
                }
            }

            return high * 16 + low;
        }

        [HttpPost]
        public ActionResult GradeDetailEdit(GradeDetailEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    Grades item = null;
                    if (model.IsNew)
                    {
                        item = (from obj in entities.Grades
                                where obj.FeeType == model.话类 &&
                                      obj.GradeID == model.GradeID
                                select obj).SingleOrDefault();

                        if (item != null)
                        {
                            TempData["Error"] = "已有同样的收费等级表！";
                            return RedirectToAction("Error", "Shared");
                        }

                        item = new Grades();
                        item.GradeID = model.GradeID;
                        item.FeeType = model.话类;

                        entities.AddToGrades(item);
                    }
                    else
                    {
                        item = (from obj in entities.Grades
                                where obj.FeeType == model.话类 &&
                                      obj.GradeID == model.GradeID
                                select obj).SingleOrDefault();

                        if (item == null)
                        {
                            TempData["Error"] = "没有找到数据！";
                            return RedirectToAction("Error", "Shared");
                        }
                    }
                    item.MinDelay = model.最小计费延时;
                    item.DurationError = model.时长误差;
                    item.DurationMin = model.最小计次次数;
                    item.ServeRatio = model.服务费缩放系数;
                    item.BaseToExtra = model.附加费按基本费的比例收取时的系数;
                    item.BaseToServe = model.服务费按基本费的比例收取时的系数;
                    item.ExtraToServe = model.附加费按服务器的比例收取时的系数;
                    item.FeeMin = model.单笔花费最小金额;
                    item.FeeMax = model.单笔花费最大金额;
                    item.MonthMin = model.包月话类收费起点;
                    item.MonthMax = model.包月话类封顶限额;
                    item.RoundDefine = get取整方法(model);

                    entities.SaveChanges();

                    return RedirectToAction("GradeDetailMgt", "Manage", new { id = item.GradeID, message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            model.AreaTypeList = loadAreaTypeList();
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult GradeDetailMonthEdit(string gradeID)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            GradeDetailMonthEditModel model = new GradeDetailMonthEditModel();

            var item = (from obj in entities.Grades
                        where obj.GradeID == gradeID &&
                              obj.FeeType.Trim() == "R"
                        select obj).SingleOrDefault();
            if (item == null)
            {
                model.IsNew = true;
            }
            else
            {
                model.月租费 = item.ServeRatio;
                model.功能费 = item.BaseToExtra;
                model.代维费 = item.BaseToServe;
                model.免费额 = item.ExtraToServe;
                model.其他费 = item.FeeMin;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult GradeDetailMonthEdit(GradeDetailMonthEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();

                    Grades item = (from obj in entities.Grades
                                   where obj.FeeType.Trim() == "R" &&
                                         obj.GradeID == model.GradeID
                                   select obj).SingleOrDefault();
                    if (item == null)
                    {
                        item = new Grades();
                        item.GradeID = model.GradeID;
                        item.FeeType = "R";

                        entities.AddToGrades(item);
                    }

                    item.ServeRatio = model.月租费;
                    item.BaseToExtra = model.功能费;
                    item.BaseToServe = model.代维费;
                    item.ExtraToServe = model.免费额;
                    item.FeeMin = model.其他费;

                    entities.SaveChanges();

                    return RedirectToAction("GradeDetailMgt", "Manage", new { id = item.GradeID, message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult GradeDetailDelete(string gradeID, string areaType)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.Grades
                            where obj.GradeID == gradeID &&
                                  obj.FeeType == areaType
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);
                entities.SaveChanges();

                return RedirectToAction("GradeDetailMgt", "Manage", new { id = item.GradeID, message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult SliceEdit(string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            SliceEditModel model = new SliceEditModel();
            if (id != null)
            {
                var item = (from obj in entities.OBJDefine
                            where obj.ObjectID.Trim() == "SLICE" &&
                                  obj.ItemID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }


                model.ID = item.ItemID.Trim();
                model.Name = item.ItemName.Trim();
                model.Remark = item.Comment == null ? null : item.Comment.Trim();
            }
            else
                model.IsNew = true;
            return View(model);
        }

        [HttpPost]
        public ActionResult SliceEdit(SliceEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    var item = (from obj in entities.OBJDefine
                                where obj.ObjectID.Trim() == "SLICE" &&
                                      obj.ItemID.Trim() == model.ID
                                select obj).SingleOrDefault();
                    if (item == null)
                    {
                        item = new OBJDefine();
                        item.ItemID = model.ID;
                        item.ObjectID = "SLICE";

                        entities.AddToOBJDefine(item);
                    }
                    item.ItemName = model.Name;
                    item.Comment = model.Remark;

                    entities.SaveChanges();

                    return RedirectToAction("SliceMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult SliceDelete(string id)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.OBJDefine
                            where obj.ObjectID.Trim() == "SLICE" &&
                                  obj.ItemID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);
                var list = from obj in entities.Slice
                           where obj.SliceID.Trim() == id
                           select obj;
                foreach (var item1 in list)
                    entities.DeleteObject(item1);
                entities.SaveChanges();

                return RedirectToAction("SliceMgt", "Manage", new { message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult SliceDetailMgt(string id, string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "分段计费管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/SliceDetailMgt");

            SliceDetailMgtModel sliceModel = new SliceDetailMgtModel();
            sliceModel.SliceList = loadSliceList(true);
            sliceModel.CurrentSlice = id;
            sliceModel.Message = message;
            if (id == null)
            {
                if (sliceModel.SliceList.Count > 0)
                    sliceModel.CurrentSlice = sliceModel.SliceList[0].ID;

            }
            sliceModel.SliceDetailList = loadSliceDetail(sliceModel.CurrentSlice);
            return View(sliceModel);
        }

        private List<UISliceDetail> loadSliceDetail(string id)
        {
            if (id == null)
                return null;

            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from tariff in entities.Slice
                       where tariff.SliceID.Trim() == id
                       orderby tariff.SliceID
                       select tariff;
            var sliceDetailList = new List<UISliceDetail>();
            foreach (var item in list)
            {
                UISliceDetail detail = new UISliceDetail();
                detail.SliceID = item.SliceID.Trim();
                detail.分段起点时间 = item.FromSeconds;
                detail.分段截止时间 = item.ToSeconds;
                detail.费率 = item.Fee;
                detail.费用类别 = (from f in StaticData.FeeTypeList
                               where f.Name == item.FeeType.Trim()
                               select f.FullName).SingleOrDefault();
                detail.计次单位 = item.UnitSecond;
                detail.是否计算计次 = item.SliceFlag;
                detail.名称 = item.Description;

                sliceDetailList.Add(detail);
            }

            return sliceDetailList;
        }

        public ActionResult SliceMgt(string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "分段计费管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/SliceMgt");

            SliceMgtModel sliceMgtModel = new SliceMgtModel();
            sliceMgtModel.SliceList = loadSliceList(false);
            sliceMgtModel.Message = message;

            return View(sliceMgtModel);
        }

        public ActionResult SliceDetailEdit(string sliceID, string name)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            SliceDetailEditModel model = new SliceDetailEditModel();
            if (name != null)
            {
                var item = (from obj in entities.Slice
                            where obj.SliceID.Trim() == sliceID &&
                                  obj.Description.Trim() == name
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                model.分段起点时间 = item.FromSeconds;
                model.分段截止时间 = item.ToSeconds;
                model.费率 = item.Fee;
                model.费用类别 = item.FeeType;
                model.计次单位 = item.UnitSecond;
                model.是否计算计次 = item.SliceFlag == "Y" ? true : false;
                model.名称 = item.Description;
            }
            else
            {
                model.IsNew = true;
            }

            model.SliceID = sliceID;
            model.FeeTypeList = loadFeeTypeList();
            return View(model);
        }

        private List<UIFeeType> loadFeeTypeList()
        {
            List<UIFeeType> list = new List<UIFeeType>()
            {
                new UIFeeType(){ID = "B",Name = "B.基本费"},
                new UIFeeType(){ID = "E",Name = "E.附加费"},
                new UIFeeType(){ID = "S",Name = "S.服务费"},
            };

            return list;
        }

        [HttpPost]
        public ActionResult SliceDetailEdit(SliceDetailEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    Slice item = null;
                    if (model.IsNew)
                    {
                        item = new Slice();
                        item.Description = model.名称;
                        item.SliceID = model.SliceID;

                        entities.AddToSlice(item);
                    }
                    else
                    {
                        item = (from obj in entities.Slice
                                where obj.Description == model.名称 &&
                                      obj.SliceID == model.SliceID
                                select obj).SingleOrDefault();

                        if (item == null)
                        {
                            TempData["Error"] = "没有找到数据！";
                            return RedirectToAction("Error", "Shared");
                        }
                    }
                    item.Description = model.名称;
                    item.FromSeconds = model.分段起点时间;
                    item.ToSeconds = model.分段截止时间;
                    item.Fee = model.费率;
                    item.FeeType = model.费用类别;
                    item.UnitSecond = model.计次单位;
                    if (model.是否计算计次)
                        item.SliceFlag = "Y";
                    else
                        item.SliceFlag = "N";

                    entities.SaveChanges();

                    return RedirectToAction("SliceDetailMgt", "Manage", new { id = item.SliceID, message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            model.FeeTypeList = loadFeeTypeList();

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult SliceDetailDelete(string sliceID, string name)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.Slice
                            where obj.Description == name &&
                                      obj.SliceID == sliceID
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);
                entities.SaveChanges();

                return RedirectToAction("SliceDetailMgt", "Manage", new { id = item.SliceID, message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult UserMgt(string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "用户管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/UserMgt");

            UserMgtModel userMgtModel = new UserMgtModel();
            userMgtModel.UserList = loadUserList();
            userMgtModel.Message = message;

            return View(userMgtModel);
        }

        private List<UIUser> loadUserList()
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from obj in entities.User
                       orderby obj.Name
                       select obj;
            var userList = new List<UIUser>();
            foreach (var item in list)
            {
                UIUser user = new UIUser();
                user.ID = item.ID;
                user.Name = item.Name.Trim();
                user.Password = item.Password.Trim();
                userList.Add(user);

                StringBuilder sb = new StringBuilder();
                var authorityList = (from a in entities.UserAuthority
                                     where a.UserID == user.ID
                                     select a).ToList();
                var authority = (from a in authorityList
                                 where a.Item == "部组管理"
                                 select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "分机查询"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "费率管理"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "优惠表管理"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "分段计费管理"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "收费等级管理"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "用户管理"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "结账"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "收款"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "待结账统计"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "账目统计"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "话务统计"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "日话务统计"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "话务状况统计"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "长途统计"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "已删除分机"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "不明话单管理"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "原始话单查询"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                authority = (from a in authorityList
                             where a.Item == "备份还原"
                             select a).SingleOrDefault();
                if (authority != null && authority.Allow)
                    sb.Append(authority.Item + " ");

                user.AuthorityText = sb.ToString();
            }

            return userList;
        }

        public ActionResult UserEdit(string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            UserEditModel model = new UserEditModel();

            if (id != null)
            {
                Guid i = Guid.Parse(id);
                var item = (from obj in entities.User
                            where obj.ID == i
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }
                model.ID = i;
                model.Name = item.Name.Trim();
                model.Password = item.Password.Trim();
                model.AuthorityList = getAuthorityList(i, entities);
            }
            else
            {
                model.IsNew = true;
                model.AuthorityList = getAuthorityList(Guid.Empty, entities);
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult UserEdit(UserEditModel model)
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            if (model.IsNew && string.IsNullOrEmpty(model.Password))
                ModelState.AddModelError("Password", "请输入密码.");
            if (ModelState.IsValid)
            {
                try
                {
                    User item = null;
                    if (model.IsNew)
                    {
                        item = new User();
                        item.ID = Guid.NewGuid();
                        item.Password = model.Password;
                        entities.AddToUser(item);
                    }
                    else
                    {
                        item = (from obj in entities.User
                                where obj.ID == model.ID
                                select obj).SingleOrDefault();

                        if (item == null)
                        {
                            TempData["Error"] = "没有找到数据！";
                            return RedirectToAction("UserMgt", "Manage", new { message = "操作成功！" });
                        }
                    }
                    item.Name = model.Name;


                    var list = (from a in entities.UserAuthority
                                where a.UserID == model.ID
                                select a);
                    foreach (var authority in list)
                        entities.DeleteObject(authority);

                    if (model.Authority == null)
                        model.Authority = string.Empty;
                    var authorityStringList = model.Authority.Split(';');
                    foreach (var authorityString in authorityStringList)
                    {
                        UserAuthority authority = new UserAuthority();
                        authority.ID = Guid.NewGuid();
                        authority.Item = authorityString;
                        authority.UserID = item.ID;
                        authority.Allow = true;

                        entities.UserAuthority.AddObject(authority);
                    }

                    entities.SaveChanges();

                    return RedirectToAction("UserMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }
            model.AuthorityList = getAuthorityList(model.ID, entities);
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        private List<UserAuthority> getAuthorityList(Guid id, SanDiDbsEntities entities)
        {
            List<UserAuthority> list = new List<UserAuthority>();

            var authorityList = (from a in entities.UserAuthority
                                 where a.UserID == id
                                 select a).ToList();
            var authority = (from a in authorityList
                             where a.Item == "部组管理"
                             select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "部组管理", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "分机查询"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "分机查询", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "费率管理"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "费率管理", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "优惠表管理"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "优惠表管理", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "分段计费管理"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "分段计费管理", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "收费等级管理"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "收费等级管理", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "用户管理"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "用户管理", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "结账"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "结账", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "收款"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "收款", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "待结账统计"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "待结账统计", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "账目统计"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "账目统计", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "话务统计"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "话务统计", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "日话务统计"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "日话务统计", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "话务状况统计"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "话务状况统计", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "长途统计"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "长途统计", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "已删除分机"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "已删除分机", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "不明话单管理"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "不明话单管理", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "原始话单查询"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "原始话单查询", Allow = false });

            authority = (from a in authorityList
                         where a.Item == "备份还原"
                         select a).SingleOrDefault();
            if (authority != null && authority.Allow)
                list.Add(authority);
            else
                list.Add(new UserAuthority() { Item = "备份还原", Allow = false });

            return list;
        }

        public ActionResult UserDelete(string id)
        {
            try
            {
                Guid i = Guid.Parse(id);
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.User
                            where obj.ID == i
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);

                var list = (from a in entities.UserAuthority
                            where a.UserID == i
                            select a);
                foreach (var authority in list)
                    entities.DeleteObject(authority);

                entities.SaveChanges();

                return RedirectToAction("UserMgt", "Manage", new { message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult ChangePassword()
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            ChangePasswordModel model = new ChangePasswordModel();

            model.ID = (Guid)Session["UserID"];
            return View(model);
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (model.NewPassword != model.ConfirmPassword)
            {
                TempData["Error"] = "新密码和确认密码不一致";
                return RedirectToAction("Error", "Shared");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();

                    User item = (from obj in entities.User
                                 where obj.ID == model.ID
                                 select obj).SingleOrDefault();

                    if (item == null)
                    {
                        TempData["Error"] = "没有找到数据！";
                        return RedirectToAction("Error", "Shared");
                    }


                    item.Password = model.NewPassword;

                    entities.SaveChanges();

                    return RedirectToAction("Message", "Shared");
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public JsonResult GetMenuTree()
        {
            List<JQTreeNode> list = new List<JQTreeNode>() 
            {
                new JQTreeNode(){ id = "1",text="1",expanded = false , hasChildren = false, classes="placeholder"},
                new JQTreeNode(){ id = "2",text="2",expanded = false , hasChildren = false, classes="placeholder"},
                new JQTreeNode(){ id = "3",text="3",expanded = true , hasChildren = true, classes="placeholder",
                    children = new List<JQTreeNode>()
                    {
                        new JQTreeNode(){ id = "3.1",text="3.1",expanded = false , hasChildren = false, classes="placeholder"},
                        new JQTreeNode(){ id = "3.2",text="3.2",expanded = false , hasChildren = false, classes="placeholder"},
                    }},
            };

            return Json(list);
        }

        public ActionResult Test()
        {
            return View();
        }

        //public ActionResult ExtMgt(string message, string groupID)
        //{
        //    if (Session["User"] == null)
        //    {
        //        return this.RedirectToAction("../Account/Login");
        //    }

        //    MenuModel model1 = (MenuModel)Session["Menu"];
        //    model1.SetMenu("Manage", "Manage/DepartmentMgt");


        //    ExtMgtModel model = new ExtMgtModel();
        //    model.DepartmentList = getDepartmentList();
        //    model.Message = message;
        //    SanDiDbsEntities entities = new SanDiDbsEntities();
        //    var extList = from e in entities.Extensions
        //                  where e.GrpNo != null
        //                  select e;
        //    model.ExtCounts = extList.Count();

        //    string id = groupID;

        //    List<UIExtension> extensionList = new List<UIExtension>();

        //    IOrderedQueryable<Extensions> list = null;
        //    if (id == "null")
        //    {
        //        var groupList = (from g in entities.NGroup
        //                         select g.ID.Trim()).ToList();
        //        list = from e in entities.Extensions
        //               where e.GrpNo == null || !groupList.Contains(e.GrpNo.Trim())
        //               orderby e.ExtNo
        //               select e;

        //        model.Group = "未分组分机";

        //        foreach (var item in list)
        //        {
        //            UIExtension extension = new UIExtension();
        //            extension.分机号码 = (item.ExtNo == null) ? null : item.ExtNo.Trim();
        //            extension.收费等级 = (item.GradeID == null) ? null : item.GradeID.Trim();
        //            extension.费率 = (item.TariffID == null) ? null : item.TariffID.Trim();
        //            extension.收费话类 = (item.Method == null) ? null : item.Method.Trim();
        //            extension.报警限额 = item.Limit;
        //            extension.月杂费 = item.MiscFee;
        //            extension.用户名 = (item.UserName == null) ? null : item.UserName.Trim();
        //            extension.地址 = (item.Address == null) ? null : item.Address.Trim();
        //            extension.机架线号 = (item.LinePosition == null) ? null : item.LinePosition.Trim();
        //            extension.分机功能 = (item.Functions == null) ? (short)0 : item.Functions.Value;
        //            extension.安装日期 = item.AcctFrom.ToShortDateString();
        //            extension.备注 = (item.Notice == null) ? null : item.Notice.Trim();

        //            extensionList.Add(extension);
        //        }
        //    }
        //    else
        //    {
        //        var dept = (from d in entities.NDepartment
        //                    where d.ID.Trim() == id
        //                    select d).SingleOrDefault();
        //        if (dept == null)
        //        {
        //            var group = (from g in entities.NGroup
        //                         where g.ID.Trim() == id
        //                         orderby g.Seq
        //                         select g).SingleOrDefault();

        //            deal(group, entities, extensionList, string.Empty);

        //            model.Group = group.Name.Trim();
        //        }
        //        else
        //        {
        //            model.IsDept = true;
        //            var groupList = (from g in entities.NGroup
        //                             where g.ParentType.Trim() == "Department" &&
        //                                   g.ParentID.Trim() == id
        //                             orderby g.Seq
        //                             select g);
        //            model.Group = dept.Name.Trim();
        //            foreach (var group in groupList)
        //                deal(group, entities, extensionList, string.Empty);
        //        }

        //        list = from e in entities.Extensions
        //               where e.GrpNo != null && e.GrpNo.Trim() == id
        //               orderby e.Seq, e.ExtNo
        //               select e;
        //    }


        //    model.GroupID = id;

        //    model.ExtensionList = extensionList;
        //    model.GradeList = loadGrade();
        //    model.GradeList.Insert(0, new UIGrade() { Name = string.Empty, ID = string.Empty });

        //    return View(model);
        //}

        public ActionResult DepartmentMgt(string message, string groupID)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "部组管理" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/DepartmentMgt");


            DepartmentMgtModel mgtModel = new DepartmentMgtModel();
            mgtModel.DepartmentList = getDepartmentList();
            mgtModel.Message = message;
            mgtModel.GroupID = groupID;

            var extList = from e in entities.Extensions
                          where e.GrpNo != null
                          select e;
            mgtModel.ExtCounts = extList.Count();


            return View(mgtModel);
        }

        private List<UIDepartment> getDepartmentList()
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();

            List<UIDepartment> departmentList = (from d in entities.NDepartment
                                                 orderby d.Seq
                                                 select new UIDepartment()
                                                 {
                                                     名称 = d.Name.Trim(),
                                                     ID = d.ID.Trim(),
                                                 }).ToList();

            foreach (var department in departmentList)
            {
                department.分组List = new List<UIGroup>();

                var list1 = from g in entities.NGroup
                            where g.ParentType.Trim() == "Department" &&
                                  g.ParentID == department.ID
                            orderby g.Seq
                            select g;
                foreach (var group1 in list1)
                {
                    UIGroup uiGroup1 = new UIGroup();
                    uiGroup1.ID = group1.ID.Trim();
                    uiGroup1.名称 = group1.Name.Trim();
                    uiGroup1.分组List = new List<UIGroup>();

                    department.分组List.Add(uiGroup1);

                    var list2 = from g in entities.NGroup
                                where g.ParentType.Trim() == "Group" &&
                                      g.ParentID == uiGroup1.ID
                                orderby g.Seq
                                select g;
                    foreach (var group2 in list2)
                    {
                        UIGroup uiGroup2 = new UIGroup();
                        uiGroup2.ID = group2.ID.Trim();
                        uiGroup2.名称 = group2.Name.Trim();
                        uiGroup2.分组List = new List<UIGroup>();

                        uiGroup1.分组List.Add(uiGroup2);

                        var list3 = from g in entities.NGroup
                                    where g.ParentType.Trim() == "Group" &&
                                          g.ParentID == uiGroup2.ID
                                    orderby g.Seq
                                    select g;
                        foreach (var group3 in list3)
                        {
                            UIGroup uiGroup3 = new UIGroup();
                            uiGroup3.ID = group3.ID.Trim();
                            uiGroup3.名称 = group3.Name.Trim();
                            uiGroup3.分组List = new List<UIGroup>();

                            uiGroup2.分组List.Add(uiGroup3);
                        }
                    }
                }
            }

            return departmentList;
        }

        public ActionResult ExtensionMgt(string id)
        {
            List<UIExtension> extensionList = new List<UIExtension>();
            ExtensionMgtModel model = new ExtensionMgtModel();
            SanDiDbsEntities entities = new SanDiDbsEntities();
            IOrderedQueryable<Extensions> list = null;
            if (id == "null")
            {
                var groupList = (from g in entities.NGroup
                                 select g.ID.Trim()).ToList();
                list = from e in entities.Extensions
                       where e.GrpNo == null || !groupList.Contains(e.GrpNo.Trim())
                       orderby e.ExtNo
                       select e;

                model.Group = "未分组分机";
                model.IsDept = true;

                foreach (var item in list)
                {
                    UIExtension extension = new UIExtension();
                    extension.分机号码 = (item.ExtNo == null) ? null : item.ExtNo.Trim();
                    extension.收费等级 = (item.GradeID == null) ? null : item.GradeID.Trim();
                    extension.费率 = (item.TariffID == null) ? null : item.TariffID.Trim();
                    extension.收费话类 = (item.Method == null) ? null : item.Method.Trim();
                    extension.报警限额 = item.Limit;
                    extension.月杂费 = item.MiscFee;
                    extension.用户名 = (item.UserName == null) ? null : item.UserName.Trim();
                    extension.地址 = (item.Address == null) ? null : item.Address.Trim();
                    extension.机架线号 = (item.LinePosition == null) ? null : item.LinePosition.Trim();
                    extension.分机功能 = (item.Functions == null) ? (short)0 : item.Functions.Value;
                    extension.安装日期 = item.AcctFrom.ToShortDateString();
                    extension.备注 = (item.Notice == null) ? null : item.Notice.Trim();

                    

                    extensionList.Add(extension);
                }
            }
            else
            {
                var dept = (from d in entities.NDepartment
                            where d.ID.Trim() == id
                            select d).SingleOrDefault();
                if (dept == null)
                {
                    var group = (from g in entities.NGroup
                                 where g.ID.Trim() == id
                                 orderby g.Seq
                                 select g).SingleOrDefault();

                    deal(group, entities, extensionList, string.Empty);
                    model.IsDept = false;
                    model.Group = group.Name.Trim();
                }
                else
                {
                    model.IsDept = true;
                    var groupList = (from g in entities.NGroup
                                     where g.ParentType.Trim() == "Department" &&
                                           g.ParentID.Trim() == id
                                     orderby g.Seq
                                     select g);
                    model.Group = dept.Name.Trim();
                    foreach (var group in groupList)
                        deal(group, entities, extensionList, string.Empty);
                }

                list = from e in entities.Extensions
                       where e.GrpNo != null && e.GrpNo.Trim() == id
                       orderby e.Seq, e.ExtNo
                       select e;
            }


            model.GroupID = id;

            model.ExtensionList = extensionList;
            model.GradeList = loadGrade();
            model.GradeList.Insert(0, new UIGrade() { Name = string.Empty, ID = string.Empty });

            foreach (var extension in model.ExtensionList)
            {
                extension.收费等级 = (from a in StaticData.GradeList
                                  where a.Name == extension.收费等级
                                  select a.FullName).SingleOrDefault();
                extension.费率 = (from a in StaticData.TariffList
                                  where a.Name == extension.费率
                                  select a.FullName).SingleOrDefault();
                if (extension.收费话类.Length > 0)
                {
                    string str = "";
                    foreach (char c in extension.收费话类)
                    {
                        if (Char.IsLetter(c))
                        {
                            str += (from a in StaticData.AreaTypeList
                                    where a.Name == c.ToString()
                                    select a.FullName).SingleOrDefault() + " ";
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (str != "")
                        extension.收费话类 = str;
                }
            }

            return View(model);
        }

        private void deal(NGroup ngroup, SanDiDbsEntities entities, List<UIExtension> extensionList, string groupName)
        {
            var list = from e in entities.Extensions
                       where e.GrpNo != null && e.GrpNo.Trim() == ngroup.ID.Trim()
                       orderby e.Seq, e.ExtNo
                       select e;
            if (groupName == string.Empty)
                groupName = ngroup.Name.Trim();
            else
                groupName = string.Format("{0} - {1}", groupName, ngroup.Name.Trim());

            foreach (var item in list)
            {
                UIExtension extension = new UIExtension();
                extension.分机号码 = (item.ExtNo == null) ? null : item.ExtNo.Trim();
                extension.收费等级 = (item.GradeID == null) ? null : item.GradeID.Trim();
                extension.费率 = (item.TariffID == null) ? null : item.TariffID.Trim();
                extension.收费话类 = (item.Method == null) ? null : item.Method.Trim();
                extension.报警限额 = item.Limit;
                extension.月杂费 = item.MiscFee;
                extension.用户名 = (item.UserName == null) ? null : item.UserName.Trim();
                extension.地址 = (item.Address == null) ? null : item.Address.Trim();
                extension.机架线号 = (item.LinePosition == null) ? null : item.LinePosition.Trim();
                extension.分机功能 = (item.Functions == null) ? (short)0 : item.Functions.Value;
                extension.安装日期 = item.AcctFrom.ToShortDateString();
                extension.备注 = (item.Notice == null) ? null : item.Notice.Trim();
                extension.分组 = groupName;

                extensionList.Add(extension);
            }

            var groupList = (from g in entities.NGroup
                             where g.ParentType.Trim() == "Group" &&
                                   g.ParentID.Trim() == ngroup.ID.Trim()
                             orderby g.Seq
                             select g);
            foreach (var group in groupList)
                deal(group, entities, extensionList, groupName);
        }

        public ActionResult DepartmentEdit(string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            DepartmentEditModel model = new DepartmentEditModel();
            if (id != null)
            {
                var item = (from obj in entities.NDepartment
                            where obj.ID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }


                model.ID = item.ID.Trim();
                model.名称 = item.Name.Trim();
            }
            else
                model.IsNew = true;
            return View(model);
        }

        [HttpPost]
        public ActionResult DepartmentEdit(DepartmentEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    var item = (from obj in entities.NDepartment
                                where obj.ID.Trim() == model.ID
                                select obj).SingleOrDefault();
                    if (item == null)
                    {
                        item = new NDepartment();
                        item.ID = "D" + Guid.NewGuid().ToString();

                        int? seq = (from d in entities.NDepartment
                                    orderby d.Seq descending
                                    select d.Seq).FirstOrDefault();
                        if (seq == null)
                            item.Seq = 0;
                        else
                            item.Seq = seq.Value + 1;

                        entities.AddToNDepartment(item);
                    }
                    item.Name = model.名称;

                    entities.SaveChanges();

                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult DepartmentDelete(string id)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.NDepartment
                            where obj.ID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                var list = from g in entities.NGroup
                           where g.ParentType.Trim() == "Department" &&
                                 g.ParentID.Trim() == item.ID.Trim()
                           select g;
                foreach (var group in list)
                    deleteGroup(group, entities);

                entities.DeleteObject(item);
                entities.SaveChanges();

                return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult GroupMotion(string id)
        {
            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/DepartmentMgt");


            GroupMotionModel mgtModel = new GroupMotionModel();
            mgtModel.DepartmentList = getDepartmentList();
            SanDiDbsEntities entities = new SanDiDbsEntities();

            NGroup group = (from d in entities.NGroup
                            where d.ID.Trim() == id
                            select d).FirstOrDefault();
            if (group == null)
            {
                TempData["Error"] = "没有找到数据！";
                return RedirectToAction("Error", "Shared");
            }

            mgtModel.ID = id;
            mgtModel.Name = group.Name.Trim();

            return View(mgtModel);
        }

        [HttpPost]
        public ActionResult GroupMotion(GroupMotionModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            string targetType = model.Target.StartsWith("D") ? "Department" : "Group";
            string targetID = model.Target;
            if (targetType.StartsWith("G") && model.Target == model.ID)
            {
                ModelState.AddModelError("Target", "迁移的分组不能和目的地相同");
            }


            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();

                NGroup group = (from d in entities.NGroup
                                where d.ID.Trim() == model.ID
                                select d).FirstOrDefault();
                if (group == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                if (targetType == "Group")
                {
                    NGroup target = (from d in entities.NGroup
                                     where d.ID.Trim() == targetID
                                     select d).SingleOrDefault();
                    if (target == null)
                    {
                        TempData["Error"] = "没有找到数据！";
                        return RedirectToAction("Error", "Shared");
                    }

                    NGroup temp = target;
                    while (temp.ParentType.Trim() == "Group")
                    {
                        temp = (from d in entities.NGroup
                                where d.ID.Trim() == temp.ParentID
                                select d).SingleOrDefault();
                        if (temp.ID.Trim() == model.ID)
                        {
                            ModelState.AddModelError("Target", "不能迁移到自己的子分组");
                            break;
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    group.ParentType = targetType;
                    group.ParentID = targetID;
                    entities.SaveChanges();

                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                }
                model.DepartmentList = getDepartmentList();
                // 如果我们进行到这一步时某个地方出错，则重新显示表单
                return View(model);

            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }

        }

        public ActionResult ExtensionMotion(string selectedItem, string groupID, bool isToSearch = false)
        {
            if (selectedItem == string.Empty)
            {
                TempData["Error"] = "请选择分机";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Manage", "Manage/DepartmentMgt");

            ExtensionMotionModel mgtModel = new ExtensionMotionModel();
            mgtModel.IsToSearch = isToSearch;
            mgtModel.DepartmentList = getDepartmentList();
            mgtModel.IdList = selectedItem;
            mgtModel.GroupID = groupID;
            SanDiDbsEntities entities = new SanDiDbsEntities();

            string[] idList = selectedItem.Split('!');
            mgtModel.ExtensionList = new List<UIExtension>();
            var list = from e in entities.Extensions
                       where idList.Contains(e.ExtNo.Trim())
                       select e;

            foreach (var item in list)
            {
                UIExtension extension = new UIExtension();
                extension.分机号码 = (item.ExtNo == null) ? null : item.ExtNo.Trim();
                extension.收费等级 = (item.GradeID == null) ? null : item.GradeID.Trim();
                extension.费率 = (item.TariffID == null) ? null : item.TariffID.Trim();
                extension.收费话类 = (item.Method == null) ? null : item.Method.Trim();
                extension.报警限额 = item.Limit;
                extension.月杂费 = item.MiscFee;
                extension.用户名 = (item.UserName == null) ? null : item.UserName.Trim();
                extension.地址 = (item.Address == null) ? null : item.Address.Trim();
                extension.机架线号 = (item.LinePosition == null) ? null : item.LinePosition.Trim();
                extension.分机功能 = (item.Functions == null) ? (short)0 : item.Functions.Value;
                extension.安装日期 = item.AcctFrom.ToShortDateString();
                extension.备注 = (item.Notice == null) ? null : item.Notice.Trim();

                mgtModel.ExtensionList.Add(extension);
            }

            return View(mgtModel);
        }

        [HttpPost]
        public ActionResult ExtensionMotion(ExtensionMotionModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }

                SanDiDbsEntities entities = new SanDiDbsEntities();
                string[] idList = model.IdList.Split('!');
                var list = from e in entities.Extensions
                           where idList.Contains(e.ExtNo.Trim())
                           select e;
                if (model.Target.StartsWith("D"))
                {
                    ModelState.AddModelError("Target", "不能选择部门");
                }

                if (ModelState.IsValid)
                {
                    var group = (from g in entities.NGroup
                                 where g.ID.Trim() == model.Target
                                 select g).SingleOrDefault();

                    foreach (var item in list)
                    {
                        item.GrpNo = model.Target;
                        if (group.GradeID != null)
                            item.GradeID = group.GradeID;
                    }

                    entities.SaveChanges();
                    if (model.IsToSearch)
                        return RedirectToAction("ExtensionSearch", "Manage", new { message = "操作成功！" });
                    else if (model.GroupID == null)
                        return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                    else
                        return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！", groupID = model.GroupID });
                }
                model.DepartmentList = getDepartmentList();
                model.ExtensionList = new List<UIExtension>();
                foreach (var item in list)
                {
                    UIExtension extension = new UIExtension();
                    extension.分机号码 = (item.ExtNo == null) ? null : item.ExtNo.Trim();
                    extension.收费等级 = (item.GradeID == null) ? null : item.GradeID.Trim();
                    extension.费率 = (item.TariffID == null) ? null : item.TariffID.Trim();
                    extension.收费话类 = (item.Method == null) ? null : item.Method.Trim();
                    extension.报警限额 = item.Limit;
                    extension.月杂费 = item.MiscFee;
                    extension.用户名 = (item.UserName == null) ? null : item.UserName.Trim();
                    extension.地址 = (item.Address == null) ? null : item.Address.Trim();
                    extension.机架线号 = (item.LinePosition == null) ? null : item.LinePosition.Trim();
                    extension.分机功能 = (item.Functions == null) ? (short)0 : item.Functions.Value;
                    extension.安装日期 = item.AcctFrom.ToShortDateString();
                    extension.备注 = (item.Notice == null) ? null : item.Notice.Trim();

                    model.ExtensionList.Add(extension);
                }

                return View(model);

            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }

        }

        public ActionResult GroupEdit(string id, string parentID, string parentType)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            GroupEditModel model = new GroupEditModel();
            if (id != null)
            {
                var item = (from obj in entities.NGroup
                            where obj.ID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }


                model.ID = item.ID.Trim();
                model.名称 = item.Name.Trim();
                model.ParentType = item.ParentType.Trim();
                model.ParentID = item.ParentID.Trim();
                if (item.GradeID == null)
                    model.收费等级 = string.Empty;
                else
                    model.收费等级 = item.GradeID;

                if (model.ParentType == "Department")
                {
                    var temp = (from d in entities.NDepartment
                                where d.ID.Trim() == model.ParentID
                                select d).SingleOrDefault();
                    model.Department = temp.Name.Trim();
                }
                else if (model.ParentType == "Group")
                {
                    var temp = (from d in entities.NGroup
                                where d.ID.Trim() == model.ParentID
                                select d).SingleOrDefault();
                    model.Group = temp.Name.Trim();
                }
            }
            else if (parentID != null && parentType != null)
            {
                model.ParentID = parentID;
                model.ParentType = parentType;
                if (model.ParentType == "Department")
                {
                    var temp = (from d in entities.NDepartment
                                where d.ID.Trim() == model.ParentID
                                select d).SingleOrDefault();
                    model.Department = temp.Name.Trim();
                }
                else if (model.ParentType == "Group")
                {
                    var temp = (from d in entities.NGroup
                                where d.ID.Trim() == model.ParentID
                                select d).SingleOrDefault();
                    model.Group = temp.Name.Trim();
                }
                model.IsNew = true;
            }
            else
            {
                return RedirectToAction("Error", "Shared");
            }
            model.GradeList = loadGrade();
            model.GradeList.Insert(0, new UIGrade() { ID = string.Empty, Name = string.Empty });
            return View(model);
        }

        [HttpPost]
        public ActionResult GroupEdit(GroupEditModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    NGroup item = null;
                    if (model.IsNew)
                    {
                        var temp = (from obj in entities.NGroup
                                    where obj.ID.Trim() == model.ID
                                    select obj).SingleOrDefault();
                        if (temp != null)
                        {
                            TempData["Error"] = "编号重复";
                            return RedirectToAction("Error", "Shared");
                        }
                        item = new NGroup();
                        item.ID = "G" + Guid.NewGuid().ToString();

                        int? seq = (from d in entities.NGroup
                                    where d.ParentType == model.ParentType &&
                                          d.ParentID == model.ParentID
                                    orderby d.Seq descending
                                    select d.Seq).FirstOrDefault();
                        if (seq == null)
                            item.Seq = 0;
                        else
                            item.Seq = seq.Value + 1;

                        entities.AddToNGroup(item);
                    }
                    else
                    {
                        item = (from obj in entities.NGroup
                                where obj.ID.Trim() == model.ID
                                select obj).SingleOrDefault();
                        if (item == null)
                        {
                            TempData["Error"] = "没有找到数据！";
                            return RedirectToAction("Error", "Shared");
                        }
                    }
                    item.Name = model.名称;
                    item.ParentID = model.ParentID;
                    item.ParentType = model.ParentType;
                    if (model.收费等级 == string.Empty || model.收费等级 == null)
                        item.GradeID = null;
                    else
                    {
                        item.GradeID = model.收费等级;

                        var list = (from e in entities.Extensions
                                    where e.GrpNo.Trim() == item.ID
                                    select e);
                        foreach (var extension in list)
                            extension.GradeID = model.收费等级;
                    }

                    entities.SaveChanges();

                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }
            model.GradeList = loadGrade();
            model.GradeList.Insert(0, new UIGrade() { ID = string.Empty, Name = string.Empty });
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult GroupDelete(string id)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.NGroup
                            where obj.ID.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }
                deleteGroup(item, entities);

                entities.SaveChanges();

                return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        private void deleteGroup(NGroup ngroup, SanDiDbsEntities entities)
        {
            var list1 = from g in entities.NGroup
                        where g.ParentType.Trim() == "Group" &&
                              g.ParentID.Trim() == ngroup.ID.Trim()
                        select g;
            foreach (var item in list1)
                entities.DeleteObject(item);

            var list2 = from g in entities.Extensions
                        where g.GrpNo.Trim() == ngroup.ID.Trim()
                        select g;
            foreach (var item in list2)
                entities.DeleteObject(item);

            entities.DeleteObject(ngroup);
        }

        public ActionResult ExtensionEdit(string groupID, string id, bool isToSearch = false)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();
            ExtensionEditModel model = new ExtensionEditModel();
            model.IsToSearch = isToSearch;
            model.SourceGroupID = groupID;
            if (id != null)
            {
                var item = (from obj in entities.Extensions
                            where obj.ExtNo.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                model.分机号码 = (item.ExtNo == null) ? null : item.ExtNo.Trim();
                model.收费等级 = (item.GradeID == null) ? null : item.GradeID.Trim();
                model.费率 = (item.TariffID == null) ? null : item.TariffID.Trim();
                model.收费话类 = (item.Method == null) ? null : item.Method.Trim();
                model.报警限额 = item.Limit;
                model.月杂费 = item.MiscFee;
                model.用户名 = (item.UserName == null) ? null : item.UserName.Trim();
                model.地址 = (item.Address == null) ? null : item.Address.Trim();
                model.分机功能 = (item.Functions == null) ? (short)0 : item.Functions.Value;
                model.机架线号 = (item.LinePosition == null) ? null : item.LinePosition.Trim();
                model.安装日期 = item.AcctFrom;
                model.备注 = (item.Notice == null) ? null : item.Notice.Trim();
                model.GroupID = (item.GrpNo == null) ? null : item.GrpNo.Trim();
            }
            else
            {
                model.IsNew = true;
                model.安装日期 = DateTime.Now;
                model.GroupID = groupID;
                if (groupID != null || groupID == "null")
                {
                    var group = (from obj in entities.NGroup
                                 where obj.ID.Trim() == groupID
                                 select obj).SingleOrDefault();
                    if (group != null)
                    {
                        if (group.GradeID == null)
                            model.收费等级 = string.Empty;
                        else
                            model.收费等级 = group.GradeID;
                    }
                }

            }


            model.TraiffList = loadTraiff();
            model.话类List = loadAreaTypeList();
            if (model.收费话类 != null)
                foreach (char c in model.收费话类)
                    foreach (var item in model.话类List)
                    {
                        if (item.ID == c.ToString())
                            item.IsSelected = true;
                    }
            model.GradeList = loadGrade();
            return View(model);
        }

        [HttpPost]
        public ActionResult ExtensionEdit(ExtensionEditModel model)
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var item = (from obj in entities.Extensions
                        where obj.ExtNo.Trim() == model.分机号码
                        select obj).SingleOrDefault();
            if (model.IsNew)
            {
                if (item != null)
                    ModelState.AddModelError("分机号码", "分机号码已存在");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (model.IsNew)
                    {
                        item = new Extensions();
                        item.ExtNo = model.分机号码;

                        int? seq = (from d in entities.Extensions
                                    where d.GrpNo.Trim() == model.GroupID
                                    orderby d.Seq descending
                                    select d.Seq).FirstOrDefault();
                        if (seq == null)
                            item.Seq = 0;
                        else
                            item.Seq = seq.Value + 1;

                        entities.AddToExtensions(item);
                    }
                    item.GradeID = model.收费等级;
                    item.TariffID = model.费率;
                    item.Method = model.收费话类;
                    item.Limit = model.报警限额;
                    item.MiscFee = model.月杂费;
                    item.UserName = model.用户名;
                    item.Address = model.地址;
                    item.Functions = model.分机功能;
                    item.LinePosition = model.机架线号;
                    item.AcctFrom = model.安装日期;
                    item.Notice = model.备注;
                    if (item.GrpNo == null)
                    {
                        if (model.GroupID == "null")
                            item.GrpNo = null;
                        else
                            item.GrpNo = model.GroupID;
                    }

                    entities.SaveChanges();

                    if (model.IsToSearch)
                        return RedirectToAction("ExtensionSearch", "Manage", new { message = "操作成功！" });
                    else if (model.SourceGroupID == null)
                        return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                    else
                        return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！", groupID = model.SourceGroupID });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }

            model.TraiffList = loadTraiff();
            model.话类List = loadAreaTypeList();
            if (model.收费话类 != null)
                foreach (char c in model.收费话类)
                    foreach (var item1 in model.话类List)
                    {
                        if (item1.ID == c.ToString())
                            item1.IsSelected = true;
                    }
            model.GradeList = loadGrade();

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public ActionResult ExtensionDelete(string id, string groupID, bool isToSearch = false)
        {
            try
            {
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var item = (from obj in entities.Extensions
                            where obj.ExtNo.Trim() == id
                            select obj).SingleOrDefault();
                if (item == null)
                {
                    TempData["Error"] = "没有找到数据！";
                    return RedirectToAction("Error", "Shared");
                }

                entities.DeleteObject(item);

                ExtensionsBak bak = new ExtensionsBak();
                bak.ID = Guid.NewGuid();
                bak.AcctFrom = item.AcctFrom;
                bak.Address = item.Address;
                bak.DelDatetime = DateTime.Now;
                bak.ExtNo = item.ExtNo;
                bak.Functions = item.Functions;
                bak.GradeID = item.GradeID;
                bak.HastGrade = item.HastGrade;
                bak.InstallDate = item.InstallDate;
                bak.Limit = item.Limit;
                bak.LinePosition = item.LinePosition;
                bak.Method = item.Method;
                bak.MiscFee = item.MiscFee;
                bak.Notice = item.Notice;
                bak.PayAcct = item.PayAcct;
                bak.Pwd = item.Pwd;
                bak.QryPwd = item.QryPwd;
                bak.SortID = item.SortID;
                bak.TariffID = item.TariffID;
                bak.UserName = item.UserName;

                var ngroup = (from g in entities.NGroup
                              where g.ID == item.GrpNo
                              select g).SingleOrDefault();
                if (ngroup != null)
                {
                    bak.Grp = ngroup.Name;
                    while (ngroup.ParentType.Trim() == "Group")
                    {
                        ngroup = (from g in entities.NGroup
                                  where g.ID == ngroup.ParentID
                                  select g).SingleOrDefault();
                        if (ngroup == null)
                            break;
                    }

                    if (ngroup != null)
                    {
                        var dept = (from g in entities.NDepartment
                                    where g.ID == ngroup.ParentID
                                    select g).SingleOrDefault();

                        if (dept != null)
                            bak.Department = dept.Name;
                    }
                }

                entities.AddToExtensionsBak(bak);

                entities.SaveChanges();

                if (isToSearch)
                    return RedirectToAction("ExtensionSearch", "Manage", new { message = "操作成功！" });
                else if (groupID == null)
                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                else
                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！", groupID = groupID });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult ExtensionBatchDelete(string phone, string groupID, bool isToSearch = false)
        {
            try
            {
                string[] idList = phone.Split('!');

                SanDiDbsEntities entities = new SanDiDbsEntities();
                var list = (from obj in entities.Extensions
                            where idList.Contains(obj.ExtNo.Trim())
                            select obj);
                foreach (var item in list)
                {
                    entities.DeleteObject(item);
                }
                entities.SaveChanges();

                if (isToSearch)
                    return RedirectToAction("ExtensionSearch", "Manage", new { message = "操作成功！" });
                else if (groupID == null)
                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                else
                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！", groupID = groupID });
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("Error", "Shared");
            }
        }

        public ActionResult ExtensionSearch(string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "分机查询" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel menu = (MenuModel)Session["Menu"];
            menu.SetMenu("Manage", "Manage/ExtensionSearch");

            ExtensionSearchModel model = new ExtensionSearchModel();
            model.Message = message;
            return View(model);
        }

        [HttpPost]
        public ActionResult ExtensionSearch(ExtensionSearchModel model)
        {
            if ((model.Extension == null || model.Extension == string.Empty) &&
                (model.User == null || model.User == string.Empty))
                ModelState.AddModelError("Extensions", "请输入分机或者用户名");

            if (ModelState.IsValid)
            {
                return this.RedirectToAction("ExtensionSearchResult", new { ext = string.Format("{0}", model.Extension), user = model.User });
            }
            return View(model);
        }

        public ActionResult ExtensionSearchResult(string ext, string user)
        {
            List<UIExtension> extensionList = new List<UIExtension>();

            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from e in entities.Extensions
                       select e;
            IOrderedQueryable<Extensions> list1 = null;

            if (ext != null && ext != string.Empty)
                list1 = from e in list
                        where e.ExtNo.IndexOf(ext) >= 0
                        orderby e.ExtNo
                        select e;

            if (user != null && user != string.Empty)
                list1 = from e in list
                        where e.UserName.IndexOf(user) >= 0
                        orderby e.ExtNo
                        select e;


            foreach (var item in list1)
            {
                UIExtension extension = new UIExtension();
                extension.分机号码 = (item.ExtNo == null) ? null : item.ExtNo.Trim();
                extension.收费等级 = (item.GradeID == null) ? null : item.GradeID.Trim();
                extension.费率 = (item.TariffID == null) ? null : item.TariffID.Trim();
                extension.收费话类 = (item.Method == null) ? null : item.Method.Trim();
                extension.报警限额 = item.Limit;
                extension.月杂费 = item.MiscFee;
                extension.用户名 = (item.UserName == null) ? null : item.UserName.Trim();
                extension.地址 = (item.Address == null) ? null : item.Address.Trim();
                extension.机架线号 = (item.LinePosition == null) ? null : item.LinePosition.Trim();
                extension.分机功能 = (item.Functions == null) ? (short)0 : item.Functions.Value;
                extension.安装日期 = item.AcctFrom.ToShortDateString();
                extension.备注 = (item.Notice == null) ? null : item.Notice.Trim();

                if (item.GrpNo == null)
                {
                    extension.部组 = "(未分组分机)";
                }
                else
                {
                    var group = (from g in entities.NGroup
                                 where g.ID.Trim() == item.GrpNo.Trim()
                                 select g).SingleOrDefault();
                    if (group != null)
                    {
                        var temp = group;
                        while (temp.ParentType.Trim() == "Group")
                        {
                            temp = (from g in entities.NGroup
                                    where g.ID.Trim() == temp.ParentID.Trim()
                                    select g).SingleOrDefault();
                        }
                        var dept = (from g in entities.NDepartment
                                    where g.ID.Trim() == temp.ParentID.Trim()
                                    select g).SingleOrDefault();

                        extension.部组 = string.Format("{0} - {1}", dept.Name.Trim(), group.Name.Trim());
                    }
                }

                extensionList.Add(extension);
            }



            ExtensionSearchResultModel model = new ExtensionSearchResultModel();
            model.ExtensionList = extensionList;

            return View(model);
        }

        public ActionResult DepartmentSort()
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            DepartmentSortModel model = new DepartmentSortModel();
            var list = getDepartmentList();
            model.List = new List<SelectListItem>();
            model.ResultList = new List<SelectListItem>();
            foreach (var item in list)
                model.List.Add(new SelectListItem() { Text = item.名称, Value = item.ID });

            return View(model);
        }

        [HttpPost]
        public ActionResult DepartmentSort(DepartmentSortModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string[] idList = model.Result.Split('!');
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    for (int i = 0; i < idList.Length; i++)
                    {
                        string id = idList[i];
                        var item = (from d in entities.NDepartment
                                    where d.ID.Trim() == id
                                    select d).SingleOrDefault();
                        item.Seq = i;
                    }
                    entities.SaveChanges();
                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }
            return View(model);
        }

        public ActionResult GroupSort(string type, string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            GroupSortModel model = new GroupSortModel();
            model.List = new List<SelectListItem>();
            model.ResultList = new List<SelectListItem>();
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from g in entities.NGroup
                       where g.ParentType.Trim() == type &&
                             g.ParentID.Trim() == id
                       orderby g.Seq
                       select g;

            StringBuilder sb = new StringBuilder();
            foreach (var item in list)
            {
                model.List.Add(new SelectListItem() { Text = item.Name.Trim(), Value = item.ID.Trim() });
                if (sb.ToString() == string.Empty)
                    sb.Append(item.ID.Trim());
                else
                    sb.Append(string.Format("!{0}", item.ID.Trim()));
            }

            model.SourceIDList = sb.ToString();
            return View(model);
        }

        [HttpPost]
        public ActionResult GroupSort(GroupSortModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();
                    if (model.Order != null)
                    {
                        string[] idList = model.SourceIDList.Split('!');
                        IOrderedQueryable<NGroup> tempList = null;

                        var list1 = from d in entities.NGroup
                                    where idList.Contains(d.ID.Trim())
                                    select d;

                        if (model.Order == "Asc")
                            tempList = list1.OrderBy(s => s.Name.Trim());
                        else if (model.Order == "Desc")
                            tempList = list1.OrderByDescending(s => s.Name.Trim());

                        var list2 = tempList.ToList();

                        for (int i = 0; i < list2.Count; i++)
                        {
                            NGroup group = list2[i];
                            group.Seq = i;
                        }
                    }
                    else
                    {
                        string[] idList = model.Result.Split('!');

                        for (int i = 0; i < idList.Length; i++)
                        {
                            string id = idList[i];
                            var item = (from d in entities.NGroup
                                        where d.ID.Trim() == id
                                        select d).SingleOrDefault();
                            item.Seq = i;
                        }
                    }
                    entities.SaveChanges();
                    return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }
            return View(model);
        }

        public ActionResult ExtensionSort(string id)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            ExtensionSortModel model = new ExtensionSortModel();
            model.List = new List<SelectListItem>();
            model.ResultList = new List<SelectListItem>();
            SanDiDbsEntities entities = new SanDiDbsEntities();
            var list = from g in entities.Extensions
                       where g.GrpNo.Trim() == id
                       orderby g.Seq
                       select g;

            StringBuilder sb = new StringBuilder();

            foreach (var item in list)
            {
                model.List.Add(new SelectListItem() { Text = string.Format("{0}({1})", item.ExtNo.Trim(), item.Address == null ? "" : item.Address.Trim()), Value = item.ExtNo.Trim() });
                if (sb.ToString() == string.Empty)
                    sb.Append(item.ExtNo.Trim());
                else
                    sb.Append(string.Format("!{0}", item.ExtNo.Trim()));
            }
            model.SourceIDList = sb.ToString();
            model.GroupID = id;
            return View(model);
        }

        [HttpPost]
        public ActionResult ExtensionSort(ExtensionSortModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    SanDiDbsEntities entities = new SanDiDbsEntities();

                    if (model.Order != null)
                    {
                        string[] idList = model.SourceIDList.Split('!');
                        IOrderedEnumerable<string> tempList = null;

                        if (model.Order == "Asc")
                            tempList = idList.OrderBy(s => s);
                        else if (model.Order == "Desc")
                            tempList = idList.OrderByDescending(s => s);

                        for (int i = 0; i < tempList.Count(); i++)
                        {
                            string id = tempList.ElementAt(i);
                            var item = (from d in entities.Extensions
                                        where d.ExtNo.Trim() == id
                                        select d).SingleOrDefault();
                            item.Seq = i;
                        }
                    }
                    else
                    {
                        string[] idList = model.Result.Split('!');

                        for (int i = 0; i < idList.Length; i++)
                        {
                            string id = idList[i];
                            var item = (from d in entities.Extensions
                                        where d.ExtNo.Trim() == id
                                        select d).SingleOrDefault();
                            item.Seq = i;
                        }
                    }
                    entities.SaveChanges();
                    if (model.GroupID == null)
                        return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！" });
                    else
                        return RedirectToAction("DepartmentMgt", "Manage", new { message = "操作成功！", groupID = model.GroupID });
                }
                catch (Exception e)
                {
                    TempData["Error"] = e.Message;
                    return RedirectToAction("Error", "Shared");
                }
            }
            return View(model);
        }
    }

}
